<template>
    <el-dialog v-model="dialogFormVisible" :title="title" @close="closeDialog" style="width:600px">
        <el-form :model="holidayForm" ref="editHolidayRef" :rules="editHolidayRules">
            <el-form-item label="休假人员" :label-width="formLabelWidth" prop="departmentList">
                <el-tree :props="props" show-checkbox :data="departmentList" ref="dataTree" node-key="userId"
                    @check="getCheckedList" />
            </el-form-item>
            <el-form-item label="考勤类型" prop="type" style="width:500px">
                <el-radio-group v-model="holidayForm.type">
                    <el-radio :value="1">假期</el-radio>
                    <el-radio :value="2">服务器故障</el-radio>
                    <el-radio :value="3">集体出差</el-radio>
                    <el-radio :value="4">工作日</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="起止时间" prop="duration" style="width:400px">
                <el-config-provider :locale="locale">
                    <el-date-picker v-model="holidayForm.duration" type="daterange" range-separator="To"
                        start-placeholder="开始时间" end-placeholder="结束时间" value-format="YYYY-MM-DD" :size="large" />
                </el-config-provider>
            </el-form-item>
            <el-form-item label="放假原因" :label-width="formLabelWidth" prop="reason" style="width:400px">
                <el-input v-model="holidayForm.reason" autocomplete="off" placeholder="请输入放假原因"></el-input>
            </el-form-item>
        </el-form>
        <template #footer style="width:400px">
            <span class="dialog-footer">
                <el-button @click="clear()">取消</el-button>
                <el-button type="primary" @click="save">保存</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script>
import { ref } from "vue";
import { httpService } from "@/utils/httpService";
import { ElMessage, ElForm, ElTree, ElConfigProvider } from "element-plus";
import { vxRule } from "@/utils/validator";
import zhCn from "element-plus/lib/locale/lang/zh-cn";

export default {
    name: "teacher",
    components: {
        ElForm,
        ElMessage,
        ElTree,
        ElConfigProvider
    },
    setup() {
        return {
            locale: zhCn,
        };
    },
    data() {
        return {
            dialogFormVisible: ref(false),
            editHolidayRef: "",
            dataTree: "",
            props: {
                children: 'childrenList',
                label: 'name',
                isLeaf: 'leaf',
                level: 'level'
            },
            holidayForm: {
                holidayName: "",
                reason: "",
                duration: "",
                departmentList: [],
                holidayId: "",
                type: "",
            },
            holidayNumbers: [],
            currentNode: "",
            // 校验规则
            editHolidayRules: {
                holidayName: vxRule(true, null, "blur"),
                duration: vxRule(true, null, "blur"),
                reason: vxRule(true, null, "blur"),
                departmentList: vxRule(true, null, "blur"),
                type: vxRule(true, null, "blur"),
            },
        };
    },
    mounted() {
        this.loadNode()
    },
    methods: {
        getCheckedList() {
            this.holidayForm.departmentList = this.$refs.dataTree.getCheckedKeys();
        },
        loadNode() {
            httpService(
                "/pythonApi/attendanceApi/teacherTree",
                {},
                "get"
            ).then((data) => {
                this.departmentList = data.list;
            });
        },
        closeDialog() {
            this.clear();
        },
        cancel() {
            this.clear();
        },
        getTeacherInfo(teacherNumber) {
            httpService("/pythonApi/teacherApi/queryById", { id: id }, "get").then(
                (data) => {
                    this.addTeacherSignInStatisticsForm = data;
                }
            );
        },
        clear() {
            this.dialogFormVisible = false;
            this.$refs.dataTree.setCheckedNodes([]);
            this.holidayForm.holidayName = "";
            this.holidayForm.reason = "";
            this.holidayForm.duration = "";
            this.holidayForm.departmentList = []
            this.holidayForm.type = ""
        },
        getHolidayById(holidayId) {
            httpService("/pythonApi/attendanceApi/getHolidayList",
                {
                    page: 1,
                    limit: 2,
                    holidayId: holidayId,
                }, "get").then(
                    (data) => {
                        let temp = data.data;
                        this.holidayForm = temp[0];
                        this.holidayForm.duration = [this.holidayForm.startDate, this.holidayForm.endDate];
                        let participants = this.holidayForm.departmentList;
                        for (let i in participants) {
                            this.$refs.dataTree.setChecked(participants[i], true, true)
                        }
                    }
                );
        },
        save() {
            this.$refs.editHolidayRef.validate((valid) => {
                if (valid) {
                    let lists = this.$refs.dataTree.getCheckedNodes(false, false), info = [], bool = [];
                    for (let i in lists) {
                        let list = lists[i];
                        if (bool[list['father']]) {
                            bool[list['userId']] = true
                        } else {
                            info.push(list['userId']);
                            bool[list['userId']] = true;
                        }
                    }
                    let params = new FormData(); //创建一个form对象,必须是form对象否则后端接受不到数据
                    params.append("reason", this.holidayForm.reason);
                    params.append("duration", this.holidayForm.duration);
                    params.append("holidayId", this.holidayForm.holidayId);
                    params.append("departmentList", JSON.stringify(info));
                    params.append("type", this.holidayForm.type);
                    httpService("/pythonApi/attendanceApi/addHoliday", params, "post").then(
                        (data) => {
                            if (data.code == 200) {
                                ElMessage.success(data.message);
                                this.clear();
                                //刷新父组件的数据
                                this.$parent.getHolidayList();
                            } else {
                                ElMessage.error(data.message);
                            }
                        }
                    );
                }
            })
        },
        getCheckedKeys(data, keys, key) {
            let res = [];
            recursion(data, false);
            return res;

            function recursion(arr, isChild) {
                let aCheck = [];
                for (let i = 0; i < arr.length; i++) {
                    let obj = arr[i];
                    aCheck[i] = false;
                    if (obj.childrenList) {
                        aCheck[i] = recursion(obj.childrenList, true) ? true : aCheck[i];
                        if (aCheck[i]) {
                            res.push(obj[key]);
                        }
                    }

                    for (let j = 0; j < keys.length; j++) {
                        if (obj[key] == keys[j]) {
                            aCheck[i] = true;
                            if (res.indexOf(obj[key]) == -1) {
                                res.push(obj[key]);
                            }
                            break;
                        }
                    }
                }
                if (isChild) {
                    return aCheck.indexOf(true) != -1;
                }
            }
        }




    },
};
</script>
<style></style>